﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Tao.OpenGl;
using OpenTK.Graphics;

namespace Clandestine
{
    public class TextSprite : Sprite
    {
        System.Drawing.Graphics grtmp;
        System.Drawing.Font font;
        bool texnull = true;

        private string text;

        public string Text
        {
            get
            {
                return text;
            }
            set
            {
                lock (Graphics.RenderLockBlob)
                {
                    if (!texnull)
                    {
                        this.Texture.Destroy();
                        texnull = true;
                    }

                    text = value;
                    redrawText(value);
                }
            }
        }

        public TextSprite(Font clandestineFont, System.Drawing.Graphics grtmp, System.Drawing.Font font, string text)
        {
            this.grtmp = grtmp;
            this.font = font;
            this.Layer = 1;
            this.Color = new GLColor(1f, 1f, 1f, 1f);

            this.Scale = 1f / Fonts.PrecisionScale;

            Text = text;
        }

        private void redrawText(string text)
        {
            Size size = grtmp.MeasureString(text, font).ToSize();

            if (size.IsEmpty)
                return;

            // Here's where we do the hard work!
            Bitmap bmp = new Bitmap(size.Width, size.Height);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            g.DrawString(text, font, Brushes.White, 0, 0);
            g.Flush(System.Drawing.Drawing2D.FlushIntention.Sync);
            g.Dispose();

            this.SetTexture(new Texture(bmp, false, true));
            texnull = false;
        }

        internal override void Render()
        {
            Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); // THE
            Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
            base.Render();
        }
    }
}
